<template>
  <el-drawer :close-on-click-modal="false" :show-close="false">
    <template #header>
      <h3 class="unselectable">分配权限</h3>
      <el-icon
        style="color: #000; font-size: 25px; filter: drop-shadow(0 0 3px #000)"
        @click="cancel($parent)"
      >
        <Close />
      </el-icon>
    </template>
    <template #default>
      <el-tree
        style="max-width: 600px"
        :data="powerArr"
        show-checkbox
        node-key="id"
        :default-checked-keys="fourthId"
        :props="defaultProps"
        default-expand-all
        ref="tree"
      />
    </template>
    <template #footer>
      <el-button type="primary" @click="cancel($parent)">取消</el-button>
      <el-button type="primary" @click="confirm($parent)">确定</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts">
export default {
  name: 'powerShare',
}
</script>

<script setup lang="ts">
import { watch, ref } from 'vue'
import { reqGetPower, reqPermission } from '../../../../api/acl/part'
import { ElMessage } from 'element-plus'
//获取树形实例
let tree = ref()
//用于收集所点击的用户id
let userId = ref<number>()
//定义用于接受四级id
let fourthId = ref([])
//接受父组件传递的数据
let powerArr = ref<any>([])
//接受父组件传递的数据
const props = defineProps({
  powerInfo: Array,
  flag: Boolean,
})

//监测父组件传递的数据的变化
watch(
  () => props.powerInfo,
  () => {
    powerArr.value = props.powerInfo
  },
  { immediate: true },
)

//取消回调
function cancel(parent: any) {
  parent.drawer2 = false
}
//树形控件数据
const defaultProps = {
  children: 'children',
  label: 'name',
}
//定义接口函数
async function getTree(row: any) {
  //赋值id
  userId.value = row.id
  //调用接口.value
  let result = await reqGetPower(row.id as number)
  /* console.log(result) */
  //赋值
  if (result.code == 200) {
    powerArr.value = result.data
    /* console.log(powerArr.value); */
    fourthId.value = filterSelectArr(powerArr.value, [])
    /* console.log(fourthId.value); */
  }
}
//定义过滤函数
function filterSelectArr(allData: any, initArr: []) {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
//定义确认回调
async function confirm(parent: any) {
  //关闭抽屉
  parent.drawer2 = false
  //携带id
  let getCheckedKeys = tree.value.getCheckedKeys()
  let getHalfCheckedKeys = tree.value.getHalfCheckedKeys()
  let idAll = getCheckedKeys.concat(getHalfCheckedKeys)
  //请求接口
  let result = await reqPermission(userId.value as number, idAll)
  /* console.log(result) */
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '修改成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
defineExpose({ getTree })
</script>

<style scoped lang="scss"></style>
